package com.wondertek.poms.dao.repo.es.impl;

import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.dao.po.SystemConfig;
import com.wondertek.poms.dao.po.es.BcHistoryVo;
import com.wondertek.poms.dao.repo.ISystemConfigDao;
import com.wondertek.poms.dao.repo.es.IBcHistoryVoDao;
import com.wondertek.poms.dao.util.ESUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author chenjijiang
 * @description
 */
@Slf4j
@Component
public class BcHistoryVoDaoImpl implements IBcHistoryVoDao {
	@Autowired
	private ISystemConfigDao systemConfigDao;

	@Override
	public Long getCount(String prdConId, String conId, String bcSide, Date bcStartTime, Date bcEndTime, String bcStatus, String userId, String firstType, String prdInfoId) {
		SystemConfig config = systemConfigDao.findByCkey("Index_PrdContDao");
		String index_name = config.getValue();
		TransportClient client = ESUtils.getTransportClient();
		SearchRequestBuilder builder = client.prepareSearch(index_name).setTypes("BcHisVO").setSearchType(SearchType.DEFAULT);
		BoolQueryBuilder qb = QueryBuilders.boolQuery();

		if (firstType != null && !firstType.equals("")) {
			qb.must(QueryBuilders.termQuery("DISPLAY_TYPE", StringUtil.nullToString(firstType)));
		}
		if (prdConId != null && !prdConId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_CONT_ID", StringUtil.nullToString(prdConId)));
		}
		if (conId != null && !conId.equals("")) {
			qb.must(QueryBuilders.termQuery("CONTENT_ID", StringUtil.nullToString(conId)));
		}
		if (bcSide != null && !bcSide.equals("")) {
			qb.must(QueryBuilders.termQuery("BC_ID", StringUtil.nullToString(bcSide)));
		}
		if (prdInfoId != null && !prdInfoId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_INFO_ID", StringUtil.nullToString(prdInfoId)));
		}
		if (bcStartTime == null && bcEndTime == null) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, -2);
			Date startDate = cal.getTime();
			cal.add(Calendar.DAY_OF_MONTH, +3);
			Date endDate = cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			qb.filter(QueryBuilders.rangeQuery("BC_TIME").from(sdf.format(startDate)).includeLower(true)
					.to(sdf.format(endDate)).includeUpper(true));
		}
		if (bcStartTime != null && bcEndTime != null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(bcStartTime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(bcEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.filter(QueryBuilders.rangeQuery("BC_TIME").from(st).includeLower(true).to(et).includeUpper(true));
		}
		if (bcStartTime != null && bcEndTime == null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(bcStartTime);
			qb.must(QueryBuilders.rangeQuery("BC_TIME").from(st).includeLower(true));
		}
		if (bcStartTime == null && bcEndTime != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(bcEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.must(QueryBuilders.rangeQuery("BC_TIME").to(et).includeUpper(true));
		}
		if (bcStatus != null && !bcStatus.equals("")) {
			qb.must(QueryBuilders.termQuery("BC_STATUS", StringUtil.nullToString(bcStatus)));
		}
		if (userId != null && !userId.equals("")) {
			if (userId.indexOf(",") < 0) {
				qb.must(QueryBuilders.termQuery("BC_PERSON", StringUtil.nullToString(userId)));
			} else {
				BoolQueryBuilder bool = QueryBuilders.boolQuery();
				String[] users = userId.split(",");
				for (int i = 0; i < users.length; i++) {
					bool.should(QueryBuilders.termQuery("BC_PERSON", StringUtil.nullToString(users[i])));
				}
				qb.filter(bool);
			}
		}
		builder.addSort(SortBuilders.fieldSort("BC_TIME").order(SortOrder.DESC));
		builder.setQuery(qb);
		log.info("index_name:" + index_name + "=====Query Build:====" + builder.toString());
		SearchResponse response = builder.execute().actionGet();
		SearchHits hits = response.getHits();
		log.info("====hits.getTotalHits:====" + hits.getTotalHits());
		return hits.getTotalHits();
	}

	@Override
	public List<BcHistoryVo> getBcsPage(int start, int limit, String prdConId, String conId, String bcSide, Date bcStartTime, Date bcEndTime, String bcStatus, String userId, String firstType, String prdInfoId) {
		SystemConfig config = systemConfigDao.findByCkey("Index_PrdContDao");
		String index_name = config.getValue();
		TransportClient client = ESUtils.getTransportClient();
		SearchRequestBuilder builder = client.prepareSearch(index_name).setTypes("BcHisVO").setSearchType(SearchType.DEFAULT);
		BoolQueryBuilder qb = QueryBuilders.boolQuery();
		if (firstType != null && !firstType.equals("")) {
			qb.must(QueryBuilders.termQuery("DISPLAY_TYPE", StringUtil.nullToString(firstType)));
		}
		if (prdConId != null && !prdConId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_CONT_ID", StringUtil.nullToString(prdConId)));
		}
		if (conId != null && !conId.equals("")) {
			qb.must(QueryBuilders.termQuery("CONTENT_ID", StringUtil.nullToString(conId)));
		}
		if (bcSide != null && !bcSide.equals("")) {
			qb.must(QueryBuilders.termQuery("BC_ID", StringUtil.nullToString(bcSide)));
		}
		if (prdInfoId != null && !prdInfoId.equals("")) {
			qb.must(QueryBuilders.termQuery("PRD_INFO_ID", StringUtil.nullToString(prdInfoId)));
		}
		if (bcStartTime == null && bcEndTime == null) {
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DAY_OF_MONTH, -2);
			Date startDate = cal.getTime();
			cal.add(Calendar.DAY_OF_MONTH, +3);
			Date endDate = cal.getTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			qb.filter(QueryBuilders.rangeQuery("BC_TIME").from(sdf.format(startDate)).includeLower(true)
					.to(sdf.format(endDate)).includeUpper(true));
		}
		if (bcStartTime != null && bcEndTime != null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(bcStartTime);
			Calendar cal = Calendar.getInstance();
			cal.setTime(bcEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.filter(QueryBuilders.rangeQuery("BC_TIME").from(st).includeLower(true).to(et).includeUpper(true));
		}
		if (bcStartTime != null && bcEndTime == null) {
			String st = new SimpleDateFormat("yyyy-mm-dd").format(bcStartTime);
			qb.must(QueryBuilders.rangeQuery("BC_TIME").from(st).includeLower(true));
		}
		if (bcStartTime == null && bcEndTime != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(bcEndTime);
			cal.add(Calendar.DAY_OF_MONTH, +1);
			String et = new SimpleDateFormat("yyyy-mm-dd").format(cal.getTime());
			qb.must(QueryBuilders.rangeQuery("BC_TIME").to(et).includeUpper(true));
		}
		if (bcStatus != null && !bcStatus.equals("")) {
			qb.must(QueryBuilders.termQuery("BC_STATUS", StringUtil.nullToString(bcStatus)));
		}
		if (userId != null && !userId.equals("")) {
			if (userId.indexOf(",") < 0) {
				qb.must(QueryBuilders.termQuery("BC_PERSON", StringUtil.nullToString(userId)));
			} else {
				BoolQueryBuilder bool = QueryBuilders.boolQuery();
				String[] users = userId.split(",");
				for (int i = 0; i < users.length; i++) {
					bool.should(QueryBuilders.termQuery("BC_PERSON", StringUtil.nullToString(users[i])));
				}
				qb.must(bool);
			}
		}
		builder.addSort(SortBuilders.fieldSort("BC_TIME").order(SortOrder.DESC));
		builder.setQuery(qb).setFrom(start).setSize(limit);
		log.info("=====GETLIST Query Build:====" + builder.toString());
		SearchResponse response = builder.execute().actionGet();
		SearchHits hits = response.getHits();

		List<BcHistoryVo> bcHistoryList = new ArrayList<BcHistoryVo>();
		for (SearchHit hit : hits.getHits()) {
			BcHistoryVo vo = new BcHistoryVo();
			vo.setPrdConId(StringUtil.nullToString(hit.getSource().get("PRD_CONT_ID")));
			vo.setConId(StringUtil.nullToString(hit.getSource().get("CONTENT_ID")));
			vo.setConName(StringUtil.nullToString(hit.getSource().get("NAME")));
			vo.setBcSide(StringUtil.nullToString(hit.getSource().get("BC_ID")));
			vo.setBcTime(StringUtil.nullToDate(hit.getSource().get("BC_TIME"), "yyyy-MM-dd'T'HH:mm:ss"));
			vo.setBcStatus(StringUtil.nullToString(hit.getSource().get("BC_STATUS")));
			vo.setRowNum(StringUtil.nullToString(hit.getSource().get("BC_LOG_ID")));
			vo.setBcPerson(StringUtil.nullToString(hit.getSource().get("BC_PERSON")));
			bcHistoryList.add(vo);
		}
		return bcHistoryList;
	}
}
